import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Input, Drawer } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProForm, { ModalForm, ProFormText, ProFormDateTimePicker } from '@ant-design/pro-form';
import ProDescriptions from '@ant-design/pro-descriptions';
import UpdateForm from './components/UpdateForm';
import { loginfo, addLoginfo, updateLoginfo, removeLoginfo } from './service';
import { useAccess } from 'umi';
/**
 * 添加节点
 *
 * @param fields
 */
const handleAdd = async (fields) => {
  const hide = message.loading('正在添加');

  try {
    await addLoginfo({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 *
 * @param fields
 */

const handleUpdate = async (fields, currentRow) => {
  const hide = message.loading('正在更新');

  try {
    await updateLoginfo({ ...currentRow, ...fields });
    hide();
    message.success('更新成功');
    return true;
  } catch (error) {
    hide();
    message.error('更新失败请重试！');
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeLoginfo(selectedRows.map((row) => row.infoId));
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList = () => {
  const access = useAccess();
  /** 新建窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState(false);
  /** 分布更新窗口的弹窗 */

  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const [showDetail, setShowDetail] = useState(false);
  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);

  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  /** 国际化配置 */

  const columns = [
    {
      title: '序号',
      dataIndex: 'infoId',
      valueType: 'text',
      hideInSearch: true,
      render: (text, record, index) => {
        return <span>{(currentPage - 1) * pageSize + index + 1}</span>;
      },
    },
    {
      title: '用户账号',
      dataIndex: 'userName',
      valueType: 'text',
    },
    {
      title: '登录IP地址',
      dataIndex: 'ipaddr',
      valueType: 'text',
    },
    {
      title: '登录地点',
      dataIndex: 'loginLocation',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '浏览器类型',
      dataIndex: 'browser',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '操作系统',
      dataIndex: 'os',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '登录状态',
      dataIndex: 'status',
      valueType: 'select',
      valueEnum: {
        0: {
          text: '成功',
        },
        1: {
          text: '失败',
        },
      },
      hideInSearch: true,
    },
    {
      title: '提示消息',
      dataIndex: 'msg',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '访问时间',
      dataIndex: 'loginTime',
      valueType: 'dateRange',
      render: (_, record) => <span>{record.loginTime}</span>,
      search: {
        transform: (value) => {
          return {
            'params[beginTime]': value[0],
            'params[endTime]': value[1],
          };
        },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            handleUpdateModalVisible(true);
            setCurrentRow(record);
          }}
        >
          修改
        </a>,
        <a
          onClick={() => {
            setCurrentRow(record);
            setShowDetail(true);
          }}
        >
          查看
        </a>,
      ],
    },
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="infoId"
        // key="logininforList"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            hidden={access.hasNoPerms('system:loginfo:add')}
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={async (params) => {
          setCurrentPage(params.current);
          setPageSize(params.pageSize);
          const serverParams = {
            ...params,
            pageNum: params.current,
            pageSize: params.pageSize,
          };
          const res = await loginfo(serverParams);
          const result = {
            data: res.rows,
            total: res.total,
            success: true,
          };
          return result;
        }}
        pagination={{
          pageSize: 10,
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}
      <ModalForm
        layout="horizontal"
        labelCol={{ span: 4 }}
        title="新建登录日志"
        width="600px"
        visible={createModalVisible}
        onVisibleChange={handleModalVisible}
        onFinish={async (value) => {
          const success = await handleAdd(value);

          if (success) {
            handleModalVisible(false);

            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          rules={[
            {
              required: true,
              message: '登录IP地址不能为空',
            },
            {
              pattern: new RegExp(
                '^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$',
                'g',
              ),
              message: '登录IP地址格式错误',
            },
          ]}
          width="md"
          name="ipaddr"
          label="登录IP地址"
          placeholder="请输入登录IP地址"
        />

        <ProFormText
          rules={[
            {
              required: true,
              message: '登录地点为必填项',
            },
          ]}
          width="md"
          label="登录地点"
          placeholder="请输入登录地点"
          name="loginLocation"
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '浏览器类型为必填项',
            },
          ]}
          width="md"
          label="浏览器类型"
          placeholder="请输入浏览器类型"
          name="browser"
        />

        <ProFormDateTimePicker
          name="loginTime"
          label="访问时间"
          rules={[
            {
              required: true,
              message: '访问时间为必填项',
            },
          ]}
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '提示消息为必填项',
            },
          ]}
          width="md"
          label="提示消息"
          placeholder="请输入提示消息"
          name="msg"
        />
      </ModalForm>
      <UpdateForm
        onSubmit={async (value) => {
          const success = await handleUpdate(value, currentRow);

          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);

            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          setCurrentRow(undefined);
        }}
        updateModalVisible={updateModalVisible}
        values={currentRow || {}}
      />

      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={true}
      >
        {currentRow?.infoId && (
          <ProDescriptions
            column={2}
            title="查看"
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.infoId,
            }}
            columns={columns.filter((item) => item.dataIndex !== 'option')}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
